﻿//////////////////////////////////////////////////////////////////////////////
//
// Copyright © 1998-2024 Glodon Company Limited.
//
// Licensed under the MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the “Software”),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////////
#pragma execution_character_set("utf-8")

// qt headers
#include "TranslatorManager.h"
#include <QtCore>
#include <QtWidgets>
#include <QLabel>
#include <QPushButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QStackedLayout>
#include <QList>

// custom headers
#include "TitleBar.h"
#include "GbmpNew.h"
#include "EnableCompileWarning_The_LAST_IncludeInCpp.h" 
namespace gmepgcs 
{
    TitleBar::TitleBar(QWidget *parent)
        : QFrame(parent)
        ,m_pParentWindow(parent)
    {
        Init();
    }

    TitleBar::~TitleBar() 
    {
    }

    void TitleBar::Init()
    {
        // title bar self
        setFixedHeight(32);

        // stacked layout
        QStackedLayout *pStackedLayout = NEW_AS_QT(QStackedLayout);
        setLayout(pStackedLayout);
        DBG_WARN_AND_RETURN_VOID_UNLESS(pStackedLayout, L"pStackedLayout为空", L"GMEP", L"2024-01-30");
        pStackedLayout->setContentsMargins(0, 0, 0, 0);
        pStackedLayout->setSpacing(0);
        pStackedLayout->setStackingMode(QStackedLayout::StackingMode::StackAll);

        // base layer widget
        pBaseLayerMainWidget = NEW_AS_QT(QWidget,this);
        DBG_WARN_AND_RETURN_VOID_UNLESS(pBaseLayerMainWidget, L"pBaseLayerMainWidget为空", L"GMEP", L"2024-01-30");
        pStackedLayout->addWidget(pBaseLayerMainWidget);

        // base layer layout
        QHBoxLayout *pBaseLayerMainLayout = NEW_AS_QT(QHBoxLayout);
        DBG_WARN_AND_RETURN_VOID_UNLESS(pBaseLayerMainLayout, L"pBaseLayerMainLayout为空", L"GMEP", L"2024-01-30");
        pBaseLayerMainWidget->setLayout(pBaseLayerMainLayout);
        pBaseLayerMainLayout->setContentsMargins(5, 0, 0, 0);
        pBaseLayerMainLayout->setSpacing(0);

        // 标题栏图标
        m_pIconLabel = NEW_AS_QT(QLabel,pBaseLayerMainWidget);
        DBG_WARN_AND_RETURN_VOID_UNLESS(m_pIconLabel, L"m_pIconLabel为空", L"GMEP", L"2024-01-30");
        m_pIconLabel->setObjectName("IconLabel");
        pBaseLayerMainLayout->addWidget(m_pIconLabel);
        m_pIconLabel->setFixedSize(24, 24);
        m_pIconLabel->setScaledContents(true);
        m_pIconLabel->setContentsMargins(0, 0, 0, 0);

        // 标题栏标题
        m_pTitleLabel = NEW_AS_QT(QLabel,pBaseLayerMainWidget);
        DBG_WARN_AND_RETURN_VOID_UNLESS(m_pTitleLabel, L"m_pTitleLabel为空", L"GMEP", L"2024-01-30");
        m_pTitleLabel->setObjectName("TitleLabel");
        pBaseLayerMainLayout->addWidget(m_pTitleLabel);
        m_pTitleLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
        QFont titleLabelFont = m_pTitleLabel->font();
        titleLabelFont.setFamily("Microsoft YaHei");
        titleLabelFont.setPixelSize(14);
        m_pTitleLabel->setFont(titleLabelFont);
        m_pTitleLabel->setStyleSheet(
            "QLabel{"
            "color:rgba(0,0,0,255);"
            "}"
        );
        m_pTitleLabel->setContentsMargins(5, 0, 0, 0);

        // control box layout
        QHBoxLayout *pControlBoxHLayout = NEW_AS_QT(QHBoxLayout);
        DBG_WARN_AND_RETURN_VOID_UNLESS(pControlBoxHLayout, L"pControlBoxHLayout为空", L"GMEP", L"2024-01-30");
        pBaseLayerMainLayout->addLayout(pControlBoxHLayout);
        pControlBoxHLayout->setContentsMargins(0, 1, 1, 2);
        pControlBoxHLayout->setSpacing(0);

        // 最小化按钮
        m_pMinButton = NEW_AS_QT(QPushButton,pBaseLayerMainWidget);
        DBG_WARN_AND_RETURN_VOID_UNLESS(m_pMinButton, L"m_pMinButton为空", L"GMEP", L"2024-01-30");
        m_pMinButton->setObjectName("MinimizeButton");
        pControlBoxHLayout->addWidget(m_pMinButton);
        m_pMinButton->setToolTip(QString::fromStdWString(GBMP_TR(L"最小化")));
        m_pMinButton->setMinimumWidth(32);
        m_pMinButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
        m_pMinButton->setStyleSheet(
            "QPushButton{"
            "background-color:rgba(0,0,0,0);"
            "background-image:url(:/images/icon_min_normal.png);"
            "background-repeat:no-repeat;"
            "background-position:center;"
            "border:0px solid;"
            "}"
            "QPushButton:hover{"
            "background-color:rgba(229, 229, 229, 255);"
            "background-image:url(:/images/icon_min_hover.png);"
            "}"
        );
        connect(m_pMinButton, &QPushButton::clicked, [=]() {
            QWidget *pWindow = m_pParentWindow;
            if (!pWindow)
            {
                return;
            }
            {
                pWindow->showMinimized();
            }
        });

        // 最大化按钮
        m_pMaxButton = NEW_AS_QT(QPushButton,pBaseLayerMainWidget);
        DBG_WARN_AND_RETURN_VOID_UNLESS(m_pMaxButton, L"m_pMaxButton为空", L"GMEP", L"2024-01-30");
        m_pMaxButton->setObjectName("MaximizeButton");
        pControlBoxHLayout->addWidget(m_pMaxButton);
        m_pMaxButton->setToolTip(QString::fromStdWString(GBMP_TR(L"最大化")));
        m_pMaxButton->setMinimumWidth(32);
        m_pMaxButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
        m_pMaxButton->setStyleSheet(
            "QPushButton{"
            "background-color:rgba(0,0,0,0);"
            "background-image:url(:/images/icon_max_normal.png);"
            "background-repeat:no-repeat;"
            "background-position:center;"
            "border:0px solid;"
            "}"
            "QPushButton:hover{"
            "background-color:rgba(229, 229, 229, 255);"
            "background-image:url(:images/icon_max_hover.png);"
            "}"
        );
        connect(m_pMaxButton, &QPushButton::clicked, [=]() {
            QWidget *pWindow = m_pParentWindow;
            if (!pWindow)
            {
                return;
            }
            {
                if (pWindow->isFullScreen())
                {
                    pWindow->setWindowFlags(Qt::Dialog);
                    pWindow->showNormal();
                    QDesktopWidget *pDesktop = QApplication::desktop();
                    DBG_WARN_AND_RETURN_VOID_UNLESS(pDesktop, L"pDesktop为空", L"GMEP", L"2024-01-30");
                    QRect screenRect = pDesktop->screenGeometry();
                    QWidget* pWidget = pWindow->parentWidget();
                    if (pWidget)
                    {
                        screenRect = pWidget->frameGeometry();
                    }
                    QSize size = pWindow->maximumSize();
                    pWindow->move((screenRect.width() - size.width()) / 2 + screenRect.x(), (screenRect.height() - size.height()) / 2 + screenRect.y());
                }
                else 
                {
                    pWindow->setWindowFlags(Qt::Dialog);
                    pWindow->showFullScreen();
                }                   
            }
        });

        // 关闭按钮
        m_pCloseButton = NEW_AS_QT(QPushButton,pBaseLayerMainWidget);
        DBG_WARN_AND_RETURN_VOID_UNLESS(m_pCloseButton, L"m_pCloseButton为空", L"GMEP", L"2024-01-30");
        m_pCloseButton->setObjectName("CloseButton");
        pControlBoxHLayout->addWidget(m_pCloseButton);
        m_pCloseButton->setToolTip(QString::fromStdWString(GBMP_TR(L"关闭")));
        m_pCloseButton->setMinimumWidth(32);
        m_pCloseButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
        m_pCloseButton->setStyleSheet(
            "QPushButton{"
            "background-color:rgba(0,0,0,0);"
            "background-image:url(:/images/icon_close_normal.png);"
            "background-repeat:no-repeat;"
            "background-position:center;"
            "border:0px solid;"
            "}"
            "QPushButton:hover{"
            "background-color:rgba(232, 17, 35, 255);"
            "background-image:url(:/images/icon_close_hover.png);"
            "}"
        );
        connect(m_pCloseButton, &QPushButton::clicked, [=]() {
            QWidget *pWindow = m_pParentWindow;
            if (!pWindow)
            {
                return;
            }

            {
                pWindow->close();
            }
        });
        
        // pin layer widget
        QWidget *pPinTipLayerMainWidget = NEW_AS_QT(QWidget,this);
        DBG_WARN_AND_RETURN_VOID_UNLESS(pPinTipLayerMainWidget, L"pPinTipLayerMainWidget为空", L"GMEP", L"2024-01-30");
        pPinTipLayerMainWidget->setObjectName("PinTipLayerWidget");
        pStackedLayout->addWidget(pPinTipLayerMainWidget);

        // pin layer layout
        QHBoxLayout *pPinTipLayerMainLayout = NEW_AS_QT(QHBoxLayout);
        DBG_WARN_AND_RETURN_VOID_UNLESS(pPinTipLayerMainLayout, L"pPinTipLayerMainLayout为空", L"GMEP", L"2024-01-30");
        pPinTipLayerMainWidget->setLayout(pPinTipLayerMainLayout);
        pPinTipLayerMainLayout->setContentsMargins(0, 0, 0, 0);
        pPinTipLayerMainLayout->setSpacing(0);

        // pin tip text
        m_pLblPinTip = NEW_AS_QT(QLabel,QString(),pPinTipLayerMainWidget);
        DBG_WARN_AND_RETURN_VOID_UNLESS(m_pLblPinTip, L"m_pLblPinTip为空", L"GMEP", L"2024-01-30");
        m_pLblPinTip->setObjectName("PinTipLabel");
        pPinTipLayerMainLayout->addWidget(m_pLblPinTip);
        pPinTipLayerMainLayout->setAlignment(Qt::AlignmentFlag::AlignHCenter | Qt::AlignmentFlag::AlignBottom);
        m_pLblPinTip->setVisible(false);
        m_pLblPinTip->setObjectName("PinTipLabel");
        m_pLblPinTip->setStyleSheet("QLabel#PinTipLabel{"
            "min-height:18;"
            "padding-left:5;"
            "padding-right:5;"
            "border:none;"
            "border-top-left-radius:2;"
            "border-top-right-radius:2;"
            "background-color:rgba(59,132,255);"
            "font-family:\"Microsoft YaHei\";"
            "font-size:10;"
            "color:rgba(255,255,255,255);"
            "}"
        );
    }
    
    void TitleBar::SetPinTip(QString tip)
    {
        DBG_WARN_AND_RETURN_VOID_UNLESS(m_pLblPinTip, L"m_pLblPinTip为空", L"GMEP", L"2024-01-30");
        m_pLblPinTip->setText(tip);
        m_pLblPinTip->setVisible(tip.trimmed().length()>0);
    }

    void TitleBar::SetMinBoxVisible(bool visible)
    {
        DBG_WARN_AND_RETURN_VOID_UNLESS(m_pMinButton, L"m_pMinButton为空", L"GMEP", L"2024-01-30");
        m_pMinButton->setVisible(visible);
    }

    void TitleBar::SetMaxBoxVisible(bool visible)
    {
        DBG_WARN_AND_RETURN_VOID_UNLESS(m_pMaxButton, L"m_pMaxButton为空", L"GMEP", L"2024-01-30");
        m_pMaxButton->setVisible(visible);
    }

    void TitleBar::SetCloseBoxVisible(bool visible)
    {
        DBG_WARN_AND_RETURN_VOID_UNLESS(m_pCloseButton, L"m_pCloseButton为空", L"GMEP", L"2024-01-30");
        m_pCloseButton->setVisible(visible);
    }

    void TitleBar::mouseDoubleClickEvent(QMouseEvent * event) 
    {
        Q_UNUSED(event);
        DBG_WARN_AND_RETURN_VOID_UNLESS(m_pMaxButton, L"m_pMaxButton为空", L"GMEP", L"2024-01-30");
        emit m_pMaxButton->clicked();
    }


    void TitleBar::mousePressEvent(QMouseEvent* e)
    {
        DBG_WARN_AND_RETURN_VOID_UNLESS(e, L"e为空", L"GMEP", L"2024-01-30");
        if (e->button() == Qt::LeftButton) {
            QRect rect = contentsRect();
            rect.adjust(3, 3, -3, 0);
            if (rect.contains(e->pos())) {
                e->accept();
                m_bPressed = true;
                m_pressPos = e->pos();
                m_moveStartPos = e->globalPos();
                return;
            }
        }
        QFrame::mousePressEvent(e);
    }

    void TitleBar::mouseMoveEvent(QMouseEvent* e)
    {
        DBG_WARN_AND_RETURN_VOID_UNLESS(e, L"e为空", L"GMEP", L"2024-01-30");
        if (!m_bPressed) {
            return QFrame::mouseMoveEvent(e);
        }

        e->accept();
        QPoint cursorPos = e->globalPos();
        QPoint pressed_pos = mapToGlobal(m_pressPos);
        QPoint offset = cursorPos - m_moveStartPos;
        if (offset.x() <= 0) {
            if (cursorPos.x() > pressed_pos.x()) {
                offset.setX(0);
            }
        }
        else {
            if (cursorPos.x() < pressed_pos.x()) {
                offset.setX(0);
            }
        }
        if (offset.y() <= 0) {
            if (cursorPos.y() > pressed_pos.y()) {
                offset.setY(0);
            }
        }
        else {
            if (cursorPos.y() < pressed_pos.y()) {
                offset.setY(0);
            }
        }
        if (offset.x() != 0 || offset.y() != 0) {
            Q_EMIT moveRequested(cursorPos, offset);
        }
        m_moveStartPos = cursorPos;
    }

    void TitleBar::mouseReleaseEvent(QMouseEvent* e)
    {
        DBG_WARN_AND_RETURN_VOID_UNLESS(e, L"e为空", L"GMEP", L"2024-01-30");
        if (m_bPressed) {
            m_bPressed = false;
            e->accept();
        }
        else {
            QFrame::mouseReleaseEvent(e);
        }
    }


    bool TitleBar::eventFilter(QObject * obj, QEvent * event)
    {
        DBG_WARN_AND_RETURN_FALSE_UNLESS(event, L"event为空", L"GMEP", L"2024-01-30");
        DBG_WARN_AND_RETURN_FALSE_UNLESS(m_pMaxButton, L"m_pMaxButton为空", L"GMEP", L"2024-01-30");
        switch (event->type()) 
        {
        case QEvent::WindowTitleChange:
        {
            QWidget *pWidget = qobject_cast<QWidget *>(obj);
            if (pWidget) 
            {
                auto title = pWidget->windowTitle();
                DBG_WARN_AND_RETURN_FALSE_UNLESS(m_pTitleLabel, L"m_pTitleLabel为空", L"GMEP", L"2024-01-30");
                m_pTitleLabel->setText(title);
                QString widgetName = QString("BaseLayerWidget_%1").arg(title);
                DBG_WARN_AND_RETURN_FALSE_UNLESS(pBaseLayerMainWidget, L"pBaseLayerMainWidget为空", L"GMEP", L"2024-01-30");
                if (pBaseLayerMainWidget->objectName() != widgetName)
                {                    
                    pBaseLayerMainWidget->setObjectName(widgetName);
                }
                return true;
            }
            break;
        }
        case QEvent::WindowIconChange: 
        {
            QWidget *pWidget = qobject_cast<QWidget *>(obj);
            if (pWidget) 
            {
                QIcon icon = pWidget->windowIcon();
                DBG_WARN_AND_RETURN_FALSE_UNLESS(m_pIconLabel, L"m_pIconLabel为空", L"GMEP", L"2024-01-30");
                m_pIconLabel->setPixmap(icon.pixmap(m_pIconLabel->size()));
                m_pIconLabel->setVisible(!icon.isNull());
                return true;
            }
            break;
        }
        case QEvent::WindowStateChange:
        case QEvent::Resize: 
        {
            QWidget *pWindow = m_pParentWindow;
            if (pWindow)
            {
                if (pWindow->isFullScreen())
                {
                    m_pMaxButton->setToolTip(QString::fromStdWString(GBMP_TR(L"还原")));
                }
                else
                {
                    m_pMaxButton->setToolTip(QString::fromStdWString(GBMP_TR(L"最大化")));
                }
            }
            return true;
        }
        default: 
        {
            break;
        }
        }

        return QWidget::eventFilter(obj, event);
    }


}